<template>
  <view class="work-main">
    <view class="form-container">
      <template v-if="fields && fields.length > 0">
        <template v-for="field in fields" :key="field.id">
          <view class="form-item" v-if="field.options && field.options.visible">
            <text
              class="form-label"
              :class="{ required: field.options && field.options.isRequired }"
            >{{ field.name }}</text
            >
            <view class="form-content">
              <!-- 根据字段类型渲染不同的表单控件 -->
              <template
                v-if="getWidget(field.valueType, field.widget) === '数字框'"
              >
                <input
                  type="number"
                  :value="localFormData[field.id]"
                  @input="(e:any) => updateFormData(field.id, e.target.value)"
                  placeholder="请输入"
                  class="form-input"
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '文本框'"
              >
                <input
                  type="text"
                  :value="localFormData[field.id]"
                  @input="(e:any) => updateFormData(field.id, e.target.value)"
                  placeholder="请输入"
                  class="form-input"
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多行文本框'"
              >
                <input
                  type="text"
                  :value="localFormData[field.id]"
                  @input="(e:any) => updateFormData(field.id, e.target.value)"
                  placeholder="请输入"
                  class="form-input"
                />
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '单选框'"
              >
                <view
                  @click="handleSelect('单选框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">
                    <template v-if="field.lookups?.length">
                      {{ field.lookups.find(lookup=>lookup.value === localFormData[field.id])!.text }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '选择框'"
              >
                <view
                  @click="handleSelect('选择框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">
                    <template v-if="field.lookups?.length">
                      {{ field.lookups.find(lookup=>lookup.value === localFormData[field.id])!.text }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多选框'"
              >
                <view
                  @click="handleSelect('多选框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '引用选择框'"
              >
                <view
                  @click="handleSelect('引用选择框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '多级选择框'"
              >
                <view
                  @click="handleSelect('多级选择框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">
                    <template v-if="field.lookups?.length">
                      {{ getFullPath(field.lookups, localFormData[field.id]) }}
                    </template>
                    <template v-else>
                      <text class="loading">未添加该子选项</text>
                    </template>
                  </text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '操作组织'"
              >
                <view
                  @click="handleSelect('操作组织', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '操作人'"
              >
                <view
                  @click="handleSelect('操作人', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '人员搜索框'"
              >
                <view
                  @click="handleSelect('人员搜索框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">
                    <template v-if="userInfoMap.get(localFormData[field.id])">
                      {{ userInfoMap.get(localFormData[field.id]).name }}
                    </template>
                    <template v-else>
                      <text class="loading">加载中...</text>
                    </template>
                  </text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '单位搜索框'"
              >
                <view
                  @click="handleSelect('单位搜索框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '群组搜索框'"
              >
                <view
                  @click="handleSelect('群组搜索框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="
                  getWidget(field.valueType, field.widget) === '组织群搜索框'
                "
              >
                <view
                  @click="handleSelect('组织群搜索框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '成员选择框'"
              >
                <view
                  @click="handleSelect('成员选择框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="
                  getWidget(field.valueType, field.widget) === '内部机构选择框'
                "
              >
                <view
                  @click="handleSelect('内部机构选择框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '日期选择框'"
              >
                <view
                  @click="handleSelect('日期选择框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">{{ localFormData[field.id] }}</text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '时间选择框'"
              >
                <view
                  @click="handleSelect('时间选择框', field)"
                  class="select-container"
                >
                  <text v-if="localFormData[field.id]">{{ localFormData[field.id] }}</text>
                  <text v-else class="placeholder">请选择</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
              <template
                v-if="getWidget(field.valueType, field.widget) === '文件选择框'"
              >
                <view
                  @click="handleSelect('文件选择框', field)"
                  class="select-container"
                >
                  <text class="placeholder">请上传</text>
                  <tm-icon name="tmicon-angle-right" :font-size="24"></tm-icon>
                </view>
              </template>
            </view>
          </view>
        </template>

        <view v-if="type === 'Primary'" class="form-item">
          <text class="form-label">备注信息</text>
          <view class="form-content">
            <input
              type="text"
              :value="contentStr"
              @input="(e:any) => updateContent(e.target.value)"
              placeholder="请输入备注信息"
              class="form-input"
            />
          </view>
        </view>
        <template v-if="type === 'Primary' && service && workDetailFormData &&btnRulesData.length>0 && detailForm.length>0">
          <view
            v-for="(item, index) in detailForm"
            :key="item.id"
          >
            <view class="form-item" style="height: 100rpx">
              <view class="form-content">
                <text class="form-label">{{ detailForm[index].name }}</text>
                <tm-button v-if="btnRulesData.find(i=>i.id===item.id).allowAdd && btnRulesData.find(i=>i.id===item.id).allowEdit" :shadow="0" text size="mini" @click="handleAddDetail(workDetailFormData[item.id][0].nodeId,item.id)"
                >新建</tm-button
                >
              </view>
            </view>
            <template v-if="workDetailFormData[item.id][0].after.length > 0">
              <view
                class="form-detail"
                v-for="item2 in workDetailFormData[item.id][0].after"
                :key="item2.id"
              >
                <view class="detail-item">
                  <view class="detail-row">
                    <view class="detail-label">唯一标识:</view>
                    <view class="detail-value">{{ item2.id }}</view>
                  </view>
                  <template
                    v-if="
                      service.model.fields[item.id] && service.model.fields[item.id].length > 0
                    "
                  >
                    <template
                      v-for="fieldDetail in service.model.fields[item.id]"
                      :key="fieldDetail.id"
                    >
                      <template v-if="fieldDetail.options && fieldDetail.options.visible">
                        <view class="detail-row">
                          <view
                            class="detail-label"
                            :class="{
                              required: fieldDetail.options && fieldDetail.options.isRequired
                            }"
                          >
                            {{ fieldDetail.name }}:</view
                          >
                          <view class="detail-value">
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '数字框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '文本框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '多行文本框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '单选框'
                              "
                            >
                              <text v-if="item2[fieldDetail.id]">
                                <template v-if="fieldDetail.lookups?.length">
                                  {{ fieldDetail.lookups.find(lookup=>lookup.value === item2[fieldDetail.id])!.text }}
                                </template>
                              </text>
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '选择框'
                              "
                            >
                              <text v-if="item2[fieldDetail.id]">
                                <template v-if="fieldDetail.lookups?.length">
                                  {{ fieldDetail.lookups.find(lookup=>lookup.value === item2[fieldDetail.id])!.text }}
                                </template>
                              </text>
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '多选框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '引用选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '多级选择框'
                              "
                            >
                              <text v-if="item2[fieldDetail.id]">
                                <template v-if="fieldDetail.lookups?.length">
                                  {{ getFullPath(fieldDetail.lookups, item2[fieldDetail.id]) }}
                                </template>
                              </text>
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '操作组织'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '操作人'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '人员搜索框'
                              "
                            >
                              <text v-if="item2[fieldDetail.id]">
                                <template v-if="userInfoMap.get(item2[fieldDetail.id])">
                                  {{ userInfoMap.get(item2[fieldDetail.id]).name }}
                                </template>
                                <template v-else>
                                  <text class="loading">加载中...</text>
                                </template>
                              </text>
                              <text v-else class="placeholder">{{item2[fieldDetail.id]}}</text>
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '单位搜索框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '群组搜索框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '组织群搜索框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '成员选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '内部机构选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '日期选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '时间选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                            <template
                              v-if="
                                getWidget(fieldDetail.valueType, fieldDetail.widget) === '文件选择框'
                              "
                            >
                              {{ item2[fieldDetail.id] }}
                            </template>
                          </view>
                        </view>
                      </template>
                    </template>
                  </template>
                  <view class="detail-row">
                    <view class="detail-label">操作:</view>
                    <tm-button
                      v-if="btnRulesData.find(i=>i.id===item.id).allowEdit"
                      transprent
                      text
                      icon="tmicon-delete-fill"
                      size="normal"
                      label="删除"
                      @click="deleteDetail(workDetailFormData[item.id][0].nodeId,item2.id)"
                    ></tm-button>
                    <tm-button
                      v-if="btnRulesData.find(i=>i.id===item.id).allowEdit"
                      transprent
                      text
                      icon="tmicon-edit"
                      size="normal"
                      label="编辑子表"
                      @click="editDetail(workDetailFormData[item.id][0].nodeId,item2.id,item.id)"
                    ></tm-button>
                  </view>
                </view>
              </view>
            </template>
          </view>
        </template>
      </template>
      <view v-else class="empty-state">
        <tm-text label="暂无表单项" />
      </view>
    </view>

    <tm-time-picker
      v-model:show="showTimePicker"
      v-model="currentDate"
      :defaultValue="currentDate"
      :modelStr="currentDate"
      @confirm="handleTimeConfirm"
      :showDetail="{
        year: true,
        month: true,
        day: true,
        hour: true,
        minute: true,
        second: true
      }"
    />
    <tm-time-picker
      v-model:show="showTimePicker2"
      v-model="currentDate2"
      :defaultValue="currentDate2"
      :modelStr="currentDate2"
      @confirm="handleTimeConfirm2"
      :showDetail="{
        year: true,
        month: true,
        day: true
      }"
    />
    <tm-picker
      @confirm="pickok"
      v-model:show="showPicker"
      :columns="pickDate"
      v-model="pick"
    ></tm-picker>
    <tm-drawer
      ref="calendarView"
      placement="bottom"
      v-model:show="showDrawer"
      :height="800"
      :beforeOk="handleDrawerOk"
    >
      <template v-if="showType === '多级选择框' && dlist && dlist.length > 0">
        <tm-cascader
          ref="textCascader"
          @cell-click="test"
          v-model="testValue"
          :defaultValue="testValue"
          :data="dlist"
        ></tm-cascader>
      </template>
      <template v-if="showType === '多选框' && boxlist && boxlist.length > 0">
        <tm-checkbox-group
          @change="boxlistchange"
          v-model="checkboxlist"
          direction="customCol"
        >
          <tm-checkbox value="apple" label="12871203"></tm-checkbox>
          <tm-checkbox value="banner" label="香蕉"></tm-checkbox>
          <tm-checkbox value="test" label="测试项"></tm-checkbox>
          <tm-checkbox value="other" label="其它水果"></tm-checkbox>
        </tm-checkbox-group>
      </template>
      <template v-if="showType === '人员搜索框'">
        <view class="search-section">
          <tm-input
            :searchWidth="120"
            v-model="searchKeyword"
            @search="search"
            prefix="tmicon-search"
            searchLabel="搜索"
          ></tm-input>
          <scroll-view
            class="search-result-list"
            scroll-y
            v-if="searchResults && searchResults.length > 0"
          >
            <view class="user-list">
              <view
                class="user-item"
                v-for="(item, index) in searchResults"
                :key="index"
                @click="handleUserSelect(item)"
              >
                <loadFileIcon :icon-type="item.typeName" />
                <view class="user-info">
                  <text class="username">{{ item.name }}</text>
                  <text class="account">简介：{{ item.remark }}</text>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </template>
    </tm-drawer>
  </view>
</template>

<script lang="ts" setup>
import { ref, nextTick, watch,onMounted } from 'vue'
import { model } from '@/ts/base'
import { XTarget } from '@/ts/base/schema'
import { getWidget } from '@/utils/work'
import tmCascader from '@/tmui/components/tm-cascader/tm-cascader.vue'
import loadFileIcon from '@/components/icon/loadFileIcon.vue'
import orgCtrl from '@/ts/controller'
import WorkFormService from '@/ts/core/work/scripting/WorkFormService'
interface Props {
  fields?: Array<model.FieldModel>
  type?: string
  rules?: model.RenderRule[]
  workFormData?: any
  service?:WorkFormService
  node?:model.WorkNodeModel
  workDetailData?:any
  detailFormData?:any[]
  content?:string
  btnRules?:any
}
interface TreeNode {
  code?: string
  icon?: string
  id: string
  info?: string
  parentId?: string
  propertyId: string
  relevanceId?: string
  remark?: string
  text: string
  value: string
  children?: TreeNode[]
}
const props = defineProps<Props>()
const contentStr = ref(props.content || '')
const showTimePicker2 = ref(false)
const localFormData = ref({ ...(props.workFormData || {}) })
const detailForm = ref(props.detailFormData||[])
const workDetailFormData = ref(props.workDetailData || {})
const btnRulesData = ref(props.btnRules || [])
const emit = defineEmits(['ValuesChange', 'changeType','validationChange','deleteDetailData'])
const showTimePicker = ref(false)
const showPicker = ref(false)
const showDrawer = ref(false)
const isSelectLastLevel = ref(false)
const pick = ref()
const pickDate = ref()
const currentDate = ref(new Date().getTime())
const currentDate2 = ref(new Date().getTime())
const dlist = ref<TreeNode[]>([])
const boxlist = ref([])
const testValue = ref([])
const dlist_crrent = ref()
const checkboxlist = ref([])
const showType = ref('')
const searchKeyword = ref('')
const searchResults = ref<XTarget[]>([])
const current_field = ref()
const userInfoMap = ref(new Map<string, any>())
const formValidation = ref(false)
const getUserInfo = async (userId: string) => {
  if (!userId) return null
  if (userInfoMap.value.has(userId)) {
    return userInfoMap.value.get(userId)
  }
  try {
    const res = await orgCtrl.user.findEntityAsync(userId)
    if (res) {
      userInfoMap.value.set(userId, res)
      return res
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
  return null
}
watch(
  [
    () => props.workFormData,
    () => props.workDetailData,
    () => localFormData.value,
    () => workDetailFormData.value
  ],
  async ([_newVal, _newDetailVal,localVal, detailVal]) => {
    if (!props.fields) return
    try {
      // 处理主表数据
      if (localVal) {
        const entries = Object.entries(localVal)
        for (const [key, value] of entries) {
          const field = props.fields.find(f => f.id === key)
          if (
            field &&
            typeof value === 'string' &&
            !userInfoMap.value.has(value) &&
            getWidget(field.valueType, field.widget) === '人员搜索框'
          ) {
            await getUserInfo(value)
          }
        }
      }
      // 处理子表数据
      if (detailForm.value) {
        console.log(detailVal,workDetailFormData.value);
        for (let index = 0; index < detailForm.value.length; index++) {
          if (detailVal[detailForm.value[index].id] && Array.isArray(detailVal[detailForm.value[index].id])) {
            for (let index2 = 0; index2 < detailVal[detailForm.value[index].id].length; index2++) {
              const detail = detailVal[detailForm.value[index].id][index2]
              for (const item of detail.after) {
                const entries = Object.entries(item)
                for (const [key, value] of entries) {
                  if (typeof value === 'string' && !userInfoMap.value.has(value)) {
                    // 获取子表字段定义，使用 detailForm 的对应索引
                    const formFields = props.service?.model.fields[detailForm.value[index].id]
                    const field = formFields?.find(f => f.id === key)
                    if (field && getWidget(field.valueType, field.widget) === '人员搜索框') {
                      await getUserInfo(value)
                    }
                  }
                }
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('处理表单数据错误:', error)
    }
  },
  { deep: true, immediate: true }
)
const initValidation = () => {
  formValidation.value = validateRequiredFields()
  emit('validationChange', formValidation.value)
}
const validateRequiredFields = () => {
  if (!props.fields) return false
  
  const requiredFields = props.fields.filter(
    field => field.options?.visible && field.options?.isRequired
  )
  
  if (requiredFields.length === 0) return true

  return requiredFields.every(field => {
    const value = localFormData.value[field.id]
    
    switch (getWidget(field.valueType, field.widget)) {
      case '数字框':
        return value !== undefined && value !== '' && !isNaN(Number(value))
      case '文本框':
      case '多行文本框':
        return value !== undefined && value.toString().trim() !== ''
      case '单选框':
      case '选择框':
      case '多级选择框':
      case '人员搜索框':
      case '日期选择框':
      case '时间选择框':
        return value !== undefined && value !== null && value !== ''
      case '多选框':
        return Array.isArray(value) && value.length > 0
      case '文件选择框':
        return value !== undefined && value !== null
      default:
        return true
    }
  })
}
watch(
  () => props.workFormData,
  () => {
    if (props.workFormData) {
      localFormData.value = { ...props.workFormData }
      initValidation()
    }
  },
  { immediate: true, deep: true }
)
onMounted(() => {
  initValidation()
})
const updateFormData = (fieldId: string, value: any) => {
  if (localFormData.value[fieldId] === value) return
  localFormData.value[fieldId] = value
  emit('ValuesChange', fieldId, value)
}
const updateContent = (value: string) => {
  if (contentStr.value === value) return
  contentStr.value = value
  emit('ValuesChange', 'content', value)
}
const test = (item: any) => {
  dlist_crrent.value = item
}
const handleUserSelect = (user: any) => {
  updateFormData(current_field.value.id, user.id)
  showDrawer.value = false
}
const buildTree = (items: TreeNode[]): TreeNode[] => {
  const itemMap = new Map<string, TreeNode>()
  const result: TreeNode[] = []

  // 首先创建一个映射
  items.forEach(item => {
    itemMap.set(item.id, { ...item })
  })

  // 构建树结构
  items.forEach(item => {
    const node = itemMap.get(item.id)!
    if (item.parentId) {
      const parent = itemMap.get(item.parentId)
      if (parent) {
        if (!parent.children) {
          parent.children = []
        }
        parent.children.push(node)
      }
    } else {
      result.push(node)
    }
  })

  // 清理空的 children 数组
  const cleanEmptyChildren = (nodes: TreeNode[]) => {
    nodes.forEach(node => {
      if (node.children?.length === 0) {
        delete node.children
      } else if (node.children) {
        cleanEmptyChildren(node.children)
      }
    })
  }

  cleanEmptyChildren(result)
  return result
}
const boxlistchange = (e: Array<string>) => {
  console.log(e)
}
const search = async (val: string) => {
  const res = await orgCtrl.user.searchTargets(val, ['人员'])
  searchResults.value = res
}
// 在需要使用的地方调用
const handleSelect = (type: string, field: any) => {
  current_field.value = field
  switch (type) {
    case '多级选择框':
      if (field.lookups) {
        const treeData = buildTree(field.lookups)
        isSelectLastLevel.value = field.options.isSelectLastLevel
        dlist.value = treeData
        nextTick(() => {
          showDrawer.value = true
          showType.value = '多级选择框'
        })
      }
      break
    case '人员搜索框':
      showDrawer.value = true
      showType.value = '人员搜索框'
      break
    case '单选框':
    case '选择框':
      pickDate.value = field.lookups
      showPicker.value = true
      break
    case '多选框':
      console.log(field)
      showDrawer.value = true
      showType.value = '多选框'
      break
    case '引用选择框':
      console.log(field)
      break
    case '操作组织':
      console.log(field)
      break
    case '操作人':
      console.log(field)
      break
    case '单位搜索框':
      console.log(field)
      break
    case '群组搜索框':
      console.log(field)
      break
    case '组织群搜索框':
      console.log(field)
      break
    case '成员选择框':
      console.log(field)
      break
    case '内部机构选择框':
      console.log(field)
      break
    case '日期选择框':
      showTimePicker2.value = true
      break
    case '时间选择框':
      showTimePicker.value = true
      break
    case '文件选择框':
      console.log(field)
      break
    default:
      break
  }
}
const pickok = (e: any) => {
  const data = pickDate.value[e[0]]
  updateFormData(current_field.value.id, data.value)
  showDrawer.value = false
}
const handleTimeConfirm = () => {
  const date = new Date(currentDate.value)
  const formatDate = date.getFullYear() + '-' + 
      String(date.getMonth() + 1).padStart(2, '0') + '-' + 
      String(date.getDate()).padStart(2, '0') + ' ' + 
      String(date.getHours()).padStart(2, '0') + ':' + 
      String(date.getMinutes()).padStart(2, '0') + ':' + 
      String(date.getSeconds()).padStart(2, '0')
  updateFormData(current_field.value.id, formatDate)
  showTimePicker.value = false
}
const handleTimeConfirm2 = () => {
  const date = new Date(currentDate2.value)
  const formatDate = date.getFullYear() + '-' + 
      String(date.getMonth() + 1).padStart(2, '0') + '-' + 
      String(date.getDate()).padStart(2, '0')
  updateFormData(current_field.value.id, formatDate)
  showTimePicker.value = false
}
const handleDrawerOk = () => {
  return new Promise((resolve) => {
    if (showType.value === '多级选择框') {
      if (!isSelectLastLevel.value || !dlist_crrent.value?.children) {
        updateFormData(current_field.value.id, dlist_crrent.value.value)
        resolve(true)
      } else {
        uni.showToast({
          title: '请选择末级分类',
          icon: 'none'
        })
        resolve(false)
      }
    } else {
      resolve(true)
    }
  })
}
const getFullPath = (lookups: model.XLookup[], targetValue: string): string => {
  const valueNode = lookups.find(item => item.value === targetValue)
  if (!valueNode) return ''

  const path: string[] = [valueNode.text]
  let currentNode = valueNode
  
  while (currentNode.parentId) {
    const parentNode = lookups.find(item => item.id === currentNode.parentId)
    if (!parentNode) break
    path.unshift(parentNode.text)
    currentNode = parentNode
  }
  
  return path.join('/')
}
const handleAddDetail = (nodeId:string,id:string) => {
  emit('changeType', 'Detail','add',nodeId,undefined,id)
}
const deleteDetail = (nodeId:string,id:string) => {
  emit('deleteDetailData',nodeId,id)
}
const editDetail = (nodeId:string,id:string,formId:string) => {
  emit('changeType', 'Detail','edit',nodeId,id,formId) 
}
</script>

<style lang="scss" scoped>
.loading {
  color: #999;
  font-size: 28rpx;
}
.work-main {
  background-color: #f3f3f3;
  min-height: 100vh;
  margin-bottom: 180rpx;
}

.form-container {
  .form-item {
    display: flex;
    flex-direction: column;
    justify-content: center;
    height: 172rpx;
    background-color: #ffffff;
    margin-bottom: 10rpx;
    padding: 0 32rpx;

    .form-label {
      margin-bottom: 20rpx;
      font-size: 28rpx;
      color: #333;

      &.required::after {
        content: '*';
        color: #ff0000;
        margin-left: 4rpx;
      }
    }

    .form-content {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .form-input {
        flex: 1;
        height: 60rpx;
        font-size: 28rpx;
      }

      .placeholder {
        font-size: 28rpx;
        color: #00000066;
      }
    }
  }
}
.select-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

.search-section {
  display: flex;
  flex-direction: column;
  width: 100%;
  padding: 20rpx;
  margin-top: 10rpx;
}

.search-result-list {
  margin-top: 20rpx;
  max-height: 400rpx;
}

.user-list {
  .user-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1px solid #eee;

    &:active {
      background-color: #f5f5f5;
    }

    .user-info {
      margin-left: 20rpx;
      flex: 1;
      display: flex;
      flex-direction: column;

      .username {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 4rpx;
      }

      .account {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
}
.form-detail {
  background-color: #FFF;
  padding: 20rpx 32rpx;
  .detail-item {
    background-color: #F3F3F3;
    padding: 20rpx 32rpx;
    margin-bottom: 10rpx;
    border-radius: 30rpx;
    .detail-row {
      display: flex;
      align-items: center;
      margin-bottom: 16rpx;
      font-size: 28rpx;

      &:first-child {
        margin-bottom: 24rpx;
      }

      .detail-label {
        color: #666666;
        min-width: 140rpx;

          &.required::after {
          content: '*';
          color: #ff0000;
          margin-left: 4rpx;
        }
      }

      .detail-value {
        color: #333333;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .detail-actions {
        display: flex;
        gap: 20rpx;

        .action-btn {
          font-size: 24rpx;
          
          &.delete {
            color: #999999;
          }
          
          &.edit {
            color: #2196F3;
          }
        }
      }
    }
  }
}
</style>
